#coding=utf-8

import urllib.request
import urllib.parse
import time
import json


def send_request():

    post_url = "https://fanyi.qq.com/api/translate"

    headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            #表示客户端支持的压缩格式,urllib2不支持gzip解压,但是requests和scrapy默认支持gzip解压
            #"Accept-Encoding": "gzip, deflate, br",
            #接受的语言,权重
            "Accept-Language": "zh-CN,zh;q=0.9",
            #长连接
            "Connection": "keep-alive",
            #传递通过urlencode转码后的表单数据长度,这里最好不固定死
            "Content-Length": "286",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie": "pt2gguin=o0527871684; RK=8FYdimVUR6; ptcz=c3c2796e7c38282eb913a6be91771ed1d060c9fd012d45b444c0d029e3b7f33b; pgv_pvi=7336137728; fy_guid=3809987f-92aa-464a-9b24-8832df4f105c; qtv=4b797b121d848cf3; qtk=YfyRU3RauPnwa94QEbk9/Y6+grKg+epVSozMNInWvjzsXGE23Vc4dPNiFQFZGp+yD4G1OnUneovLDDjAvYad9rSBH3VB3fefXc1YxWAcLiajXDuNPLfGp6HqNAg8KTl/n1Vl9J1gGaMxx445blg5vA==; pgv_info=ssid=s5832770806; ts_last=fanyi.qq.com/; ts_refer=www.baidu.com/link; pgv_pvid=2964260971; ts_uid=2664470903; openCount=1; gr_user_id=f74bf57f-c4e0-46e3-9ebc-c71cd48b5425; 9c118ce09a6fa3f4_gr_session_id=a5b95321-617c-456e-bce5-ea46e0935317; 9c118ce09a6fa3f4_gr_session_id_a5b95321-617c-456e-bce5-ea46e0935317=true; grwng_uid=683f752e-6a01-4569-906b-4e59028be000",
            "Host": "fanyi.qq.com",
            "Origin": "https://fanyi.qq.com",
            "Referer": "https://fanyi.qq.com/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
            #表示是ajaxi异步请求
            "X-Requested-With": "XMLHttpRequest",
            }

    #构建表单数据
    form_data = {
            "source": "auto",
            "target": "en",
            "sourceText": input("请输入需要翻译的词: "),
            #qtv/qtk是cookie中参数
            "qtv": "4b797b121d848cf3",
            "qtk": "YfyRU3RauPnwa94QEbk9/Y6+grKg+epVSozMNInWvjzsXGE23Vc4dPNiFQFZGp+yD4G1OnUneovLDDjAvYad9rSBH3VB3fefXc1YxWAcLiajXDuNPLfGp6HqNAg8KTl/n1Vl9J1gGaMxx445blg5vA==",
            #此数据字段根据UNIX时间戳处理
            "sessionUuid": "translate_uuid"+str(int(time.time()*1000)),
            }
    #字典转查询字符串
    form_data = urllib.parse.urlencode(form_data).encode("utf-8")
    #根据表单数据,更改Content-Length长度
    headers["Content-Length"] = len(form_data)

    #构造post请求对象
    request = urllib.request.Request(post_url, data=form_data, headers=headers)
    #发送请求,返回响应对象
    response = urllib.request.urlopen(request)
    #读取响应对象
    response_data = response.read()
    #将json字符串转为对应的python数据类型
    response_data = json.loads(response_data.decode("utf-8"))
    #输出翻译结果
    print(response_data["translate"]["records"][0]["targetText"])



if __name__ == "__main__":
    send_request()

